package com.xxx.blog.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.blog.domain.ArticleType;
import com.xxx.blog.query.ArticleTypeQuery;
import com.xxx.blog.service.impl.ArticleTypeServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/articleType")
@Api(tags = "文章类型管理类")
public class ArticleTypeController {
    @Autowired
    private ArticleTypeServiceImpl articleTypeService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public R<List<ArticleType>> findAll() {
        List<ArticleType> articleTypeList = articleTypeService.findAll();
        return R.ok(articleTypeList);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询一个")
    public R<ArticleType> findOne(@PathVariable Long id) {
        ArticleType articleType = articleTypeService.findOne(id);
        return R.ok(articleType);
    }

    @PostMapping
    @ApiOperation(value = "分页查询")
    public R<PageInfo<ArticleType>> queryPage(@RequestBody ArticleTypeQuery articleTypeQuery) {
        List<ArticleType> articleTypeList = articleTypeService.queryPage(articleTypeQuery);
        PageInfo<ArticleType> info = new PageInfo<>(articleTypeList);
        return R.ok(info);
    }

    @PutMapping
    @ApiOperation(value = "添加或修改")
    public R<Void> addOrUpdateArticleType(@RequestBody ArticleType articleType) {
        try {
            Long id = articleType.getId();
            if (id == null) {
                articleTypeService.addArticleType(articleType);
            } else {
                articleTypeService.updateArticleType(articleType);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一个")
    public R<Void> delete(@PathVariable Long id) {
        try {
            articleTypeService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation("批量删除")
    public R<Void> batchDeletes(@RequestBody Long[] ids) {
        try {
            articleTypeService.batchDeletes(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @GetMapping("/getTypeTree/{id}")
    @ApiOperation(value = "查询所有")
    public R<List<ArticleType>> getTypeTree(@PathVariable Long id) {
        List<ArticleType> articleTypeList = articleTypeService.getTypeTree(id);
        return R.ok(articleTypeList);
    }
}
